<script setup lang="ts">
// ----------------------- 导入相关依赖 -----------------------
import {nextTick, onMounted, onUnmounted, reactive, ref} from "vue";
import {ElMessage, FormInstance} from "element-plus";
import SysDialog from "@/components/dialog/SysDialog.vue";
import useDialog from "@/hooks/useDialog";
import useInstance from "@/hooks/useInstance";
import {addProjectDocumentApi, deleteProjectDocumentApi, editProjectDocumentApi, getProjectDocumentListApi} from "@/api/project";
// 图标组件
import {Search, Refresh, Plus, Edit, Delete} from '@element-plus/icons-vue'
import {ProjectDocument, ProjectDocumentListParam} from "@/api/project/type";
import {getListApi } from "@/api/user"; // 导入获取项目列表的API
import {getSimpleCustomer } from "@/api/companyCustomer"; // 导入获取项目列表的API


// ----------------------- 组件状态定义 -----------------------
const {dialog, onShow, onClose} = useDialog()
const {global} = useInstance()

// 表格高度自适应
const tableHeight = ref(0)

// ----------------------- 表格相关 -----------------------
const tableData = ref([])
const loading = ref(false)
const paginationData = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10
})

// 定义人员接口类型
interface Person {
  id: number;
  name: string;
}

// 定义人员接口类型
interface CompanyCustomer {
  id: number;
  companyName: string;
}
// 项目列表
const personList = ref<Person[]>([])
const companyCustomerList = ref<CompanyCustomer[]>([])

// 获取人员列表
const getPersonList = async () => {
  const res = await getListApi({page: 1, limit: 1000})
  personList.value = res.data.list
}
// 获取客户列表
const getSimpleCustomerList = async () => {
  const res = await getSimpleCustomer()
  companyCustomerList.value = res.data
}


// 项目状态映射
const statusOptions = [
  { value: 0, label: '进行中' },
  { value: 1, label: '已完成' },
  { value: 2, label: '已暂停' },
  { value: 3, label: '已取消' }
]

// 获取状态显示文本
const getStatusText = (status: number) => {
  const option = statusOptions.find(item => item.value === status)
  return option ? option.label : '-'
}

// 状态标签类型
const getStatusType = (status: number) => {
  switch (status) {
    case 0: return 'primary' // 进行中
    case 1: return 'success' // 已完成
    case 2: return 'warning' // 已暂停
    case 3: return 'danger'  // 已取消
    default: return 'info'
  }
}

// ----------------------- 查询表单相关 -----------------------
const searchForm = reactive<ProjectDocumentListParam>({
  name: undefined,
  code: undefined,
  customer: undefined,
  status: undefined,
  page: 1,
  limit: 10
})

// 查询方法
const search = () => {
  paginationData.currentPage = 1
  getTableData()
}

// 重置查询
const reset = () => {
  searchForm.name = undefined
  searchForm.code = undefined
  searchForm.customer = undefined
  searchForm.status = undefined
  search()
}

// ----------------------- 表格数据处理 -----------------------
const getTableData = async () => {
  loading.value = true
  try {
    searchForm.page = paginationData.currentPage
    searchForm.limit = paginationData.pageSize
    let res = await getProjectDocumentListApi(searchForm)
    if (res && res.data) {
      tableData.value = res.data.list
      paginationData.total = res.data.total
    }
  } catch (error) {
    console.error('获取表格数据失败:', error)
  } finally {
    loading.value = false
  }
}

// ----------------------- 新增/编辑表单相关 -----------------------
const addFormRef = ref<FormInstance>()
const addForm = reactive<ProjectDocument>({
  id: undefined,
  name: undefined,
  code: undefined,
  manager: undefined,
  startDate: undefined,
  endDate: undefined,
  status: 0, // 默认为进行中
  description: undefined,
  budget: undefined,
  actualCost: undefined,
  person: undefined,
  customerId: undefined,
})

// 表单校验规则
const rules = {
  name: [{required: true, message: '请输入项目名称', trigger: 'blur'}],
  code: [{required: true, message: '请输入项目编号', trigger: 'blur'}],
  customer: [{required: true, message: '请输入客户名称', trigger: 'blur'}],
  manager: [{required: true, message: '请输入项目经理', trigger: 'blur'}],
  startDate: [{required: true, message: '请选择开始日期', trigger: 'change'}],
  status: [{required: true, message: '请选择项目状态', trigger: 'change'}]
}

// 打开新增弹框
const openAdd = () => {
  dialog.title = '新增项目档案'
  dialog.width = 900
  dialog.height = 500
  onShow()
}

// 打开编辑弹框
const openEdit = (row: ProjectDocument) => {
  dialog.title = '编辑项目档案'
  dialog.width = 900
  dialog.height = 500
  nextTick(() => {
    Object.assign(addForm, row)
  })
  onShow()
}

// 关闭弹框
const closeDialog = () => {
  addFormRef.value?.resetFields()
  Object.assign(addForm, {
    id: undefined,
    name: undefined,
    code: undefined,
    customer: undefined,
    manager: undefined,
    startDate: undefined,
    endDate: undefined,
    status: 0,
    description: undefined,
    budget: undefined,
    actualCost: undefined,
    person: undefined
  })
  onClose()
}

// 提交表单
const submit = async () => {
  await addFormRef.value?.validate()
  try {
    // 设置关联字段的显示名称
    const selectedCustomer = companyCustomerList.value.find(item => item.id === addForm.customer);
    const selectedManager = personList.value.find(item => item.id === addForm.manager);
    const selectedPerson = personList.value.find(item => item.id === addForm.person);
    
    // 确保表单对象的完整性 - 这里不需要设置显示字段，后端会处理
    // 后端应该在返回项目列表时填充这些显示字段
    
    // 提交表单数据
    if (addForm.id) {
      await editProjectDocumentApi(addForm)
      ElMessage.success('编辑成功')
    } else {
      await addProjectDocumentApi(addForm)
      ElMessage.success('新增成功')
    }
    getTableData()
    closeDialog()
  } catch (error) {
    console.error('提交失败:', error)
  }
}

// ----------------------- 删除相关 -----------------------
const deleteOne = async (id: number) => {
  const confirm = await global.$myConfirm('确定要删除吗？')
  if (confirm) {
    try {
      await deleteProjectDocumentApi(id)
      ElMessage.success('删除成功')
      if (tableData.value.length === 1 && paginationData.currentPage > 1) {
        paginationData.currentPage--
      }
      getTableData()
    } catch (error) {
      console.error('删除失败:', error)
    }
  }
}

// ----------------------- 生命周期钩子 -----------------------
onMounted(() => {
  // 获取客户列表
  getSimpleCustomerList()
  // 获取人员列表
  getPersonList()
  // 表格数据
  getTableData()
  // 设置表格高度
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
})

// 监听窗口大小变化
const handleResize = () => {
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
}

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

// ----------------------- 工具函数 -----------------------
// 格式化日期时间为仅显示日期
const formatDate = (dateTimeStr: string) => {
  if (!dateTimeStr) return '';
  
  try {
    // 尝试创建日期对象
    const date = new Date(dateTimeStr);
    if (isNaN(date.getTime())) {
      return dateTimeStr; // 如果不是有效日期，则返回原始字符串
    }
    
    // 格式化为YYYY-MM-DD
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  } catch (e) {
    console.error('日期格式化错误:', e);
    return dateTimeStr;
  }
}

// 查找关联字段的显示名称
const findDisplayName = (id: number | undefined, list: any[], labelField: string = 'name') => {
  if (!id || !list || list.length === 0) return '-';
  const item = list.find(item => item.id === id);
  return item ? item[labelField] : '-';
}
</script>

<template>
  <el-main class="project-document-main">
    <div class="main-container">
      <!-- 查询表单区域 -->
      <el-card class="search-card" shadow="hover">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="项目名称">
            <el-input v-model="searchForm.name" placeholder="请输入项目名称" clearable />
          </el-form-item>
          <el-form-item label="项目编号">
            <el-input v-model="searchForm.code" placeholder="请输入项目编号" clearable />
          </el-form-item>
          <el-form-item label="客户名称">
            <el-select v-model="searchForm.customer" placeholder="请选择客户" clearable filterable class="search-select">
              <el-option
                v-for="item in companyCustomerList"
                :key="item.id"
                :label="item.companyName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item class="search-buttons">
            <el-button type="primary" :icon="Search" @click="search" class="search-btn">
              查询
            </el-button>
            <el-button :icon="Refresh" @click="reset" class="reset-btn">
              重置
            </el-button>
            <el-button type="success" :icon="Plus" @click="openAdd" class="add-btn">
              新增
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 表格区域 -->
      <el-card class="table-card" shadow="hover">
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          :height="tableHeight"
          class="data-table"
        >
          <el-table-column type="index" label="序号" width="70" align="center"/>              
          <el-table-column prop="name" label="项目名称" min-width="150" align="center" />
          <el-table-column prop="code" label="项目编号" min-width="120" align="center" />
          <el-table-column label="客户名称" min-width="150" align="center">
            <template #default="scope">
              {{ findDisplayName(scope.row.customer, companyCustomerList, 'companyName') }}
            </template>
          </el-table-column>
          <el-table-column label="项目经理" min-width="120" align="center">
            <template #default="scope">
              {{ findDisplayName(scope.row.manager, personList) }}
            </template>
          </el-table-column>
          <el-table-column label="起止日期" min-width="240" align="center">
            <template #default="scope">
              <div class="date-range">
                <span>{{ scope.row.startDate ? formatDate(scope.row.startDate) : '-' }}</span>
                <span class="range-separator">至</span>
                <span>{{ scope.row.endDate ? formatDate(scope.row.endDate) : '未定' }}</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="项目状态" min-width="100" align="center">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="业务员" min-width="120" align="center">
            <template #default="scope">
              {{ findDisplayName(scope.row.person, personList) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="budget" label="项目预算" min-width="120" align="center">
            <template #default="scope">
              <span class="budget-value">{{ scope.row.budget ? `¥${scope.row.budget}` : '-' }}</span>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="160" fixed="right" align="center">
            <template #default="scope">
              <div class="action-buttons">
                <el-button type="primary" size="small" :icon="Edit" @click="openEdit(scope.row)" class="edit-btn">
                  编辑
                </el-button>
                <el-button type="danger" size="small" :icon="Delete" @click="deleteOne(scope.row.id)" class="delete-btn">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          v-model:current-page="paginationData.currentPage"
          v-model:page-size="paginationData.pageSize"
          :page-sizes="[10, 20, 50]"
          :total="paginationData.total"
          layout="total, sizes, prev, pager, next"
          class="pagination"
          @size-change="getTableData"
          @current-change="getTableData"
        />
      </el-card>
    </div>

    <!-- 新增/编辑弹框 -->
    <sys-dialog
      :title="dialog.title"
      :width="dialog.width"
      :visible="dialog.visible"
      :height="dialog.height"
      @onClose="closeDialog"
      @onConfirm="submit"
    >
      <template #content>
        <div class="dialog-content">
          <el-form
            ref="addFormRef"
            :model="addForm"
            :rules="rules"
            label-width="90px"
            class="add-form"
          >
            <el-card class="form-card" shadow="never">
              <template #header>
                <div class="form-header">
                  <span>基本信息</span>
                </div>
              </template>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="项目名称" prop="name">
                    <el-input v-model="addForm.name" placeholder="请输入项目名称" class="full-width" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="项目编号" prop="code">
                    <el-input v-model="addForm.code" placeholder="请输入项目编号" class="full-width" />
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="客户名称" prop="customerId">
                    <el-select v-model="addForm.customerId" placeholder="请选择客户名称" filterable class="full-width">
                      <el-option
                        v-for="item in companyCustomerList"
                        :key="item.id"
                        :label="item.companyName"
                        :value="item.id">
                      </el-option>
                    </el-select>                               </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="项目经理" prop="manager">
                    <el-select v-model="addForm.manager" placeholder="请选择项目经理" filterable class="full-width">
                      <el-option
                        v-for="item in personList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                    </el-select>                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="开始日期" prop="startDate">
                    <el-date-picker
                      v-model="addForm.startDate"
                      type="datetime"
                      placeholder="选择开始日期"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      class="full-width"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="结束日期" prop="endDate">
                    <el-date-picker
                      v-model="addForm.endDate"
                      type="datetime"
                      placeholder="选择结束日期"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      class="full-width"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="项目状态" prop="status">
                    <el-select v-model="addForm.status" placeholder="请选择项目状态" class="full-width">
                      <el-option
                        v-for="item in statusOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="业务员" prop="person">
                    <el-select v-model="addForm.person" placeholder="请选择业务员" filterable class="full-width">
                      <el-option
                        v-for="item in personList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

              </el-row>
            </el-card>

            <el-card class="form-card" shadow="never">
              <template #header>
                <div class="form-header">
                  <span>财务信息</span>
                </div>
              </template> 
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="项目预算">
                    <el-input-number
                      v-model="addForm.budget"
                      :precision="2"
                      :step="1000"
                      :min="0"
                      placeholder="请输入项目预算"
                      class="full-width"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="实际费用">
                    <el-input-number
                      v-model="addForm.actualCost"
                      :precision="2"
                      :step="1000"
                      :min="0"
                      placeholder="请输入实际费用"
                      class="full-width"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>
            
            <el-card class="form-card" shadow="never">
              <template #header>
                <div class="form-header">
                  <span>项目描述</span>
                </div>
              </template>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="描述">
                    <el-input
                      v-model="addForm.description"
                      type="textarea"
                      :rows="4"
                      placeholder="请输入项目描述"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>
          </el-form>
        </div>
      </template>
    </sys-dialog>
  </el-main>
</template>

<style scoped lang="scss">
.project-document-main {
  padding: 0;
}

.main-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  transition: all 0.3s;
  
  :deep(.el-card__body) {
    padding: 15px 20px;
  }
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  
  .el-form-item {
    margin-bottom: 0;
    margin-right: 16px;
  }
  
  .search-select {
    width: 220px;
  }
  
  .search-buttons {
    margin-left: auto;
    
    .el-button {
      margin-left: 8px;
      transition: all 0.3s;
      
      &:first-child {
        margin-left: 0;
      }
    }
    
    .search-btn {
      background: linear-gradient(135deg, #1989fa, #0056b3);
      border: none;
      
      &:hover {
        opacity: 0.9;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(25, 137, 250, 0.3);
      }
    }
    
    .add-btn {
      background: linear-gradient(135deg, #67c23a, #409eff);
      border: none;
      
      &:hover {
        opacity: 0.9;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
      }
    }
    
    .reset-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(144, 147, 153, 0.2);
    }
  }
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  height: calc(100vh - 180px);
  margin-bottom: 0;
  
  :deep(.el-card__body) {
    padding: 0;
    height: 100%;
    display: flex;
    flex-direction: column;
  }
}

.data-table {
  border-radius: 4px;
  flex: 1;
  
  :deep(.el-table__header-wrapper) {
    th {
      background-color: #f2f6fc;
      font-weight: 600;
    }
  }
  
  :deep(.el-table__row) {
    &:hover {
      td {
        background-color: #ecf5ff;
      }
    }
  }
  
  .date-range {
    display: flex;
    justify-content: center;
    align-items: center;
    
    .range-separator {
      margin: 0 6px;
      color: #909399;
    }
  }
  
  .budget-value {
    font-weight: 600;
    color: #409eff;
  }
  
  .action-buttons {
    display: flex;
    justify-content: center;
    
    .el-button {
      padding: 6px 10px;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-2px);
      }
    }
    
    .edit-btn {
      margin-right: 10px;
    }
  }
}

.pagination {
  padding: 15px 20px;
  justify-content: flex-end;
  background: #fff;
  border-radius: 0 0 8px 8px;
}

.dialog-content {
  padding: 10px;
}

.add-form {
  .form-card {
    margin-bottom: 15px;
    border-radius: 8px;
    transition: all 0.3s;
    overflow: hidden;
    border: 1px solid #ebeef5;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    :deep(.el-card__header) {
      padding: 10px 15px;
      background: linear-gradient(90deg, #f0f9eb, #e1f3d8);
      border-bottom: 1px solid #e1f3d8;
    }
    
    .form-header {
      font-size: 16px;
      font-weight: 600;
      color: #67c23a;
    }
  }
  
  :deep(.el-input), :deep(.el-select), :deep(.el-input-number), :deep(.el-date-editor) {
    width: 100%;
  }
  
  :deep(.el-input__wrapper), :deep(.el-textarea__inner) {
    box-shadow: 0 0 0 1px #dcdfe6 inset;
    
    &:hover {
      box-shadow: 0 0 0 1px #c0c4cc inset;
    }
    
    &.is-focus {
      box-shadow: 0 0 0 1px #67c23a inset;
    }
  }
  
  :deep(.el-form-item__label) {
    font-weight: 500;
  }
}

.full-width {
  width: 100%;
}
</style> 
